﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;

namespace ImagePoof
{
    public partial class frmPoof : Form
    {
        public string[] appargs;

        public frmPoof(string[] args)
        {
            InitializeComponent();
            appargs = PoofLib.RemoveNonImages(args);
        }

        private void frmPoof_Load(object sender, EventArgs e)
        {
            this.Text = "Poof! " + appargs.Length + " Images Loaded";
            txtArguments.Focus();
        }

        private void ProcessFile(string f)
        {
            txtArguments.Text = "Processing " + f + "...";
            txtArguments.Refresh();
            try
            {
                EncoderParameter ep = new EncoderParameter(Encoder.Quality, 50);
                EncoderParameters eps = new EncoderParameters(1);
                eps.Param[0] = ep;
                FileStream fs = new FileStream(f, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                Image i = Image.FromStream(fs);
                fs.Close();
                string[] actions = txtArguments.Tag.ToString().Split(' ');
                string suffix = "";
                foreach (string act in actions)
                {
                    string xact = act.ToLower();
                    if (xact == "flipx")
                        i.RotateFlip(RotateFlipType.RotateNoneFlipX);
                    if (xact == "flipy")
                        i.RotateFlip(RotateFlipType.RotateNoneFlipY);
                    if (xact == "flipxy")
                        i.RotateFlip(RotateFlipType.RotateNoneFlipXY);
                    if (xact == "rotate90")
                        i.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    if (xact == "rotate180")
                        i.RotateFlip(RotateFlipType.Rotate180FlipNone);
                    if (xact == "rotate270")
                        i.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    if(xact.Contains("scale:"))
                    {
                        float perc = Convert.ToSingle(xact.Substring(6));
                        float newHeight = (float)i.Height * ((float)0.01 * perc);
                        float newWidth = (float)i.Width * ((float)0.01 * perc);

                        i = PoofLib.ResizeImage(i, (int)newWidth, (int)newHeight);
                    }
                    if (xact.Contains("suffix:"))
                    {
                        suffix = xact.Substring(7);
                    }
                    if (xact.Contains("osuffix:"))
                    {
                        string osuffix = xact.Substring(8);
                        System.IO.File.Move(f, System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + osuffix + System.IO.Path.GetExtension(f));
                    }
                    if (xact.Contains("width:"))
                    {
                        int width = Convert.ToInt32(xact.Substring(6));
                        i = PoofLib.ResizeImage(i, width, i.Height);
                    }
                    if (xact.Contains("height:"))
                    {
                        int height = Convert.ToInt32(xact.Substring(7));
                        i = PoofLib.ResizeImage(i, i.Width, height);
                    }
                    if ((xact == "grayscale") || (xact == "gs"))
                        i = PoofLib.MakeGrayscale(new Bitmap(i));
                    if ((xact == "delete") || (xact == "del"))
                        System.IO.File.Delete(f);
                    if (xact == "save")
                    {
                        System.IO.File.Delete(f);
                        if (System.IO.Path.GetExtension(f).ToLower() == ".jpg") i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        if (System.IO.Path.GetExtension(f).ToLower() == ".jpeg") i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        if (System.IO.Path.GetExtension(f).ToLower() == ".png") i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".png", System.Drawing.Imaging.ImageFormat.Png);
                        if (System.IO.Path.GetExtension(f).ToLower() == ".gif") i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
                        if (System.IO.Path.GetExtension(f).ToLower() == ".ico") i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".ico", System.Drawing.Imaging.ImageFormat.Icon);
                        if (System.IO.Path.GetExtension(f).ToLower() == ".bmp") i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                        if (System.IO.Path.GetExtension(f).ToLower() == ".tiff") i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".tiff", System.Drawing.Imaging.ImageFormat.Tiff);
                    }
                    if ((xact == "savejpg")||(xact == "savejpeg"))
                        i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    if (xact == "savepng")
                        i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".png", System.Drawing.Imaging.ImageFormat.Png);
                    if (xact == "savegif")
                        i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
                    if (xact == "saveico")
                        i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".ico", System.Drawing.Imaging.ImageFormat.Icon);
                    if (xact == "savebmp")
                        i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                    if (xact == "savetiff")
                        i.Save(System.IO.Path.GetDirectoryName(f) + "\\" + System.IO.Path.GetFileNameWithoutExtension(f) + suffix + ".tiff", System.Drawing.Imaging.ImageFormat.Tiff);
                }
                i.Dispose();
            }
            catch (Exception e)
            {
                MessageBox.Show("Error on File: " + f + "\n" + "Details: " + e.Message + "\n\nPossible Causes:\n- You may be trying to save a file with the same extension it already has. If this is intended, try using the 'suffix:[text]' argument to append text to the new file name.\n- The file may not be an image.\n\nPress OK to Continue.", "Error Processing Image", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            
        }

        private void txtArguments_KeyUp(object sender, KeyEventArgs e)
        {
            if (txtArguments.ReadOnly)
                return;

            if (e.KeyCode == Keys.Return)
            {
                if (txtArguments.Text == "")
                    return;

                if ((txtArguments.Text.ToLower() == "exit")||(txtArguments.Text.ToLower() == "quit"))
                {
                    Application.Exit();
                }
                else if (txtArguments.Text.ToLower() == "clear")
                {
                    this.Text = "Poof! 0 Images Loaded";
                    appargs = new string[] { };
                    txtArguments.Text = "";
                }
                else if (txtArguments.Text.ToLower() == "about")
                {
                    frmAbout f = new frmAbout();
                    f.Show();
                    txtArguments.Text = "";
                }
                else if (txtArguments.Text.ToLower() == "queue")
                {
                    frmQueue f = new frmQueue(this);
                    f.Show();
                    txtArguments.Text = "";
                }
                else if (txtArguments.Text.ToLower() == "help")
                {
                    string mb = "Valid Commands (Seperate with a space):\n\n";
                    mb += "flipx - flip image over the x-axis\n";
                    mb += "flipy - flip image over the y-axis\n";
                    mb += "flipxy - flip image over the x-axis and y-axis\n";
                    mb += "rotate90 - rotate image 90 degrees clockwise\n";
                    mb += "rotate180 - rotate image 180 degrees clockwise\n";
                    mb += "rotate270 - rotate image 270 degrees clockwise\n";
                    mb += "grayscale/gs - convert the image to grayscale\n";
                    mb += "scale:[1-99] - scale image to [1-99] percent (ex: scale:25)\n";
                    mb += "suffix:[text] - appends [text] to ends of filenames (ex: suffix:_new)\n";
                    mb += "osuffix:[text] - appends [text] to ends of old filenames (ex: suffix:_old)\n";
                    mb += "width:[#] - sets the absolute width to [#] (ex: width:1280)\n";
                    mb += "height:[#] - sets the absolute height to [#] (ex: height:720)\n";
                    mb += "delete/del - deletes the original file (do this before save command)\n";
                    mb += "save - overwrites original and saves as the same file type\n";
                    mb += "savejpg/savejpeg - saves changes as a jpg (use as the last command)\n";
                    mb += "savepng - saves changes as a png (use as the last command)\n";
                    mb += "savegif - saves changes as a gif (use as the last command)\n";
                    mb += "saveico - saves changes as a ico (use as the last command)\n";
                    mb += "savebmp - saves changes as a bmp (use as the last command)\n";
                    mb += "savetiff - saves changes as a tiff (use as the last command)\n";
                    mb += "queue - view, add, and remove all the images in the queue\n";
                    mb += "clear - clears all the images in the queue\n";
                    mb += "about - information about this app\n";
                    mb += "exit/quit - closes the application (can also use ESC key)\n";

                    MessageBox.Show(mb);
                    txtArguments.Text = "";
                }
                else if ((appargs.Length >= 1) && (txtArguments.Text != ""))
                {
                    txtArguments.ReadOnly = true;
                    txtArguments.Tag = txtArguments.Text + " ";
                    this.Text = "Poof! Actions: " + txtArguments.Text;
                    for (int x = 0; x < appargs.Length; x++)
                    {
                        ProcessFile(appargs[x]);
                    }
                    Application.Exit();
                }
                else if ((appargs.Length == 0) && (txtArguments.Text != ""))
                {
                    txtArguments.Text = "";
                    MessageBox.Show("You must add one or more images to the queue.\nDrag and drop them to the text box, or type queue to manage the queue.", "Empty Queue", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }

        private void txtArguments_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
                e.Effect = DragDropEffects.All;
        }

        private void txtArguments_DragDrop(object sender, DragEventArgs e)
        {
            string[] droppedFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
            appargs = PoofLib.RemoveNonImages(droppedFiles);
            this.Text = "Poof! " + appargs.Length + " Images Loaded";
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}
